package com.techvision.ip2regionproject.service;

import com.techvision.ip2regionproject.dto.IpRegionDTO;
import org.lionsoul.ip2region.xdb.Searcher;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class Ip2RegionService {
    @Resource
    private Searcher searcher;

    public IpRegionDTO searchParseDto(String ip) {
        String region;
        try {
            region = searcher.search(ip);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        String[] parts = region.split("\\|");
        IpRegionDTO dto = new IpRegionDTO();
        dto.setCountry("0".equals(parts[0]) ? null : parts[0]);
        dto.setProvince("0".equals(parts[2]) ? null : parts[2]);
        dto.setCity("0".equals(parts[3]) ? null : parts[3]);
        dto.setIsp("0".equals(parts[4]) ? null : parts[4]);
        return dto;
    }
}